﻿using Sustainalytics.LongRunningTaskManager.Interface;

namespace Sustainalytics.LongRunningTaskManager
{
    /// <summary>
    /// Process task results in a series of stages.
    /// Any processing stage may be decorated by another stage thus permitting chainability.
    /// </summary>
    public class LongRunningTaskFileResultTransformer : ILongRunningTaskResultTransformer
    {
        /// <summary>
        /// File path where the result may be saved in case of persisting the in memory result to disk.
        /// </summary>
        public string FileDirectory { get; private set; }


        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="fileDirectory"> File path where the file may be saved. </param>
        public LongRunningTaskFileResultTransformer(string fileDirectory)
        {
            this.FileDirectory = fileDirectory;
        }


        /// <summary>
        /// Process task results which may yield another result or the passed result.
        /// </summary>
        /// <param name="result">  </param>
        /// <returns></returns>
        public ILongRunningTaskResult Process(ILongRunningTaskResult result, LongRunningTaskContext taskContext)
        {
            ILongRunningTaskResult newResult = result;

            // process only files located in memory
            if (result is LongRunningTaskFileInMemResult)
            {
                LongRunningTaskFileInMemResult fileInMemRes = result as LongRunningTaskFileInMemResult;

                if (fileInMemRes.EnforceInMemory)
                {
                    newResult = fileInMemRes;
                }
                else
                {
                    // convert in-memory file to a file stored on disk
                    var fileOnDiskRes = LongRunningTaskFileOnDiskResult.FromFileInMemResult(
                        fileDirectory: this.FileDirectory,
                        fileInMemRes: fileInMemRes);

                    newResult = fileOnDiskRes;
                }
            }

            return newResult;
        }
    }
}
